import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class Listener implements Runnable {
	private ServerSocket serverSocket;

	public Listener(ServerProfile s) throws IOException {
		serverSocket = new ServerSocket(s.getPort());
		serverSocket.setSoTimeout(1000000);
		new Thread(this, s + "").start();
	}

	public void run() {
		while (true) {
			try (Socket server = serverSocket.accept()) {
				ObjectInputStream in = new ObjectInputStream(
						server.getInputStream());
				Object obj = in.readObject();
				Message msg = (Message) obj;
				if (msg instanceof SearchMessage) {
					int key = ((SearchMessage)msg).getKey();
					boolean found = Server.localSearch(key);
					SearchResponseMessage srMsg = new SearchResponseMessage(Server.profile, new ServerProfile[] {msg.getSender()}, found);
					new Sender(srMsg, msg.getSender());
				} else if (msg instanceof SearchResponseMessage) {
					Server.searchResponseQueue.add((SearchResponseMessage) msg);
				} else if (msg instanceof RequestMessage) {
					RequestMessage m = (RequestMessage) msg;
//					System.out.println("Received " + msg);
					KeyValuePair t = Server.localCommand(m.getTuple(), m.getCommand());
					ResponseMessage resp = new ResponseMessage(new ServerProfile[] {msg.getSender()}, Server.profile, ((RequestMessage) msg).getId(), t , t!=null);
					new Sender(resp, msg.getSender());
				} else if (msg instanceof ResponseMessage) {
//					System.out.println("Listener receives a response from " + msg.getSender() + " with ID " + msg.getId());
//					System.out.println("Current queue map: " + Server.respMap);
					Server.respMap.get(msg.getId()).add(msg);
				}
				in.close();
			} catch (SocketTimeoutException s) {
				System.out.println("Socket timed out!");
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
}